package com.nginx.web.util;

import lombok.Data;

import java.sql.Connection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.function.Supplier;

@Data
public class DatabasePool {

    private BlockingQueue<Connection> queue = new ArrayBlockingQueue<>(1000);

    private static Integer MAX_CONN_NUMBER = 20;

    public Connection getConnection() {
        try {
            if (queue.isEmpty()) {
                return actualGet.get();
            } else {
                return queue.take();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void sendBackConnection(Connection connection) {
        try {
            if(queue.size() > MAX_CONN_NUMBER){
                Connection take = queue.take();
                take.close();
            }
            queue.put(connection);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Supplier<Connection> actualGet;

}
